<template>
    <div>
        <el-header height="36px">
            <header-title :title="title" />
        </el-header>
        <component v-if="prjDetail.prjType" :is="page" v-for="page in pageSetting" :key="page" :ref="page"
            :prj-stage="'SJ'" :prj-type="prjDetail.prjType" :process-inst-id="processInstId"
            :prj-id="String(prjDetail.prjId)" :basicPrjDetail="basicPrjDetail" :prjDetail="prjDetail"
            :workDetail="workDetail" @sendCancellStocks="sendCancellStocks" />
        <t-page-btn v-if="showtype && btnList.length > 0" :btn-list="btnList" @handleBtn="handleBtn" />
        <!-- 下一步 -->
        <next-page v-if="nextVisible" ref="nextPage" :visible.sync="nextVisible"
            :activity-inst-id="workDetail.activityInstID" :process-inst-id="workDetail.processInstID"
            :activity-def-id="workDetail.activityDefID" :process-def-name="workDetail.processDefName"
            @doNextEntity="nextPageRes" :route="routetype" />
        <!-- 回退 -->
        <Back-page v-if="backVisible" ref="backPage" :visible.sync="backVisible"
            :process-inst-id="workDetail.processInstID" :act-inset-id="workDetail.activityInstID"
            @doReturn="backPageRes" />
        <!-- 转派 -->
        <TransferPage v-if="transferPageVisible" :visible.sync="transferPageVisible"
            :process-inst-id="workDetail.processInstID" :org-id="workDetail.orgId" :org-code="workDetail.orgCode"
            @redeployEntity="redeployEntity" />
    </div>
</template>

<script>
import ReviewReducerOders from './mainPage/reviewReduceOrders.vue';
import ReviewReduceWastage from './mainPage/reviewReduceWastage.vue'
import HeaderTitle from '@/components/basic/HeaderTitle'
import TPageBtn from '@/components/basic/TPageBtn.vue'
import JnPrjDetail from '@/components/jn/JnPrjDetail.vue'
import ZrAttachmetl from '@/components/zr/ZrAttachmetl.vue'
import JnTaskDetail from '@/components/jn/JnTaskDetail.vue'
import { getWFWorkItem } from '@/api/actualBudget/index'
import {
    getAudit,
    getMaterialReturn,
    getConfirmPersonList,
    getSpecialCheck,
    getRouteParams,
    getPrjDetailApi,
    getSubmitCheck
} from "@/api/declinebank/index"
import { clonePage } from '@/utils'
import BackPage from '@/components/nextPerson/BackPage.vue'
import NextPage from '@/components/nextPerson/NextPage.vue'
import TransferPage from '@/components/nextPerson/ReassignPageNew.vue'
export default {
    name: "DeclineBank",
    components: {
        ReviewReducerOders,
        HeaderTitle,
        TPageBtn,
        ReviewReduceWastage,
        JnPrjDetail,
        ZrAttachmetl,
        JnTaskDetail,
        NextPage,
        BackPage,
        TransferPage
    },
    data() {
        return {
            pageSetting: ['JnPrjDetail', 'ReviewReduceWastage', 'ReviewReducerOders', 'ZrAttachmetl', 'JnTaskDetail'],
            title: "",
            btnList: [],
            prjDetail: {},
            workDetail: {},
            processInstId: "",
            basicPrjDetail: {},
            nextVisible: false,
            backVisible: false,
            transferPageVisible: false,
            routetype: ''
        }
    },
    computed: {
        showtype() {
            return this.$route.query.type === 'todo'
        }
    },
    created() {
        const { workItemId, prjId, processInstId, bizseq } = this.$route.query
        this.processInstId = processInstId || ''
        if (workItemId) {
            this.getWorkDetail(workItemId)
        }
        if (prjId) {
            this.getPrjDetail(prjId, bizseq)
        }
    },
    methods: {
        // 获取基本信息
        async getPrjDetail(prjId, bizseq) {
            const { code, data } = await getPrjDetailApi({ prjId: prjId })
            if (+code === 200) {
                this.prjDetail = data
                this.title = this.prjDetail.prjName
                await this.getAuditInfo(bizseq)
            }
        },
        // 获取流程信息
        async getWorkDetail(workItemId) {
            const { code, data } = await getWFWorkItem({ workItemId: workItemId })
            if (+code === 200) {
                this.workDetail = data
                const { bizObject } = data
                this.processInstId = data?.processInstID
                this.btnList = JSON.parse(bizObject?.buttonConfig) || []
                await this.getPrjDetail(bizObject.prjId, bizObject.bizSeq)
            }
        },
        // 获取基本信息
        async getAuditInfo(bizseq) {
            const { code, data } = await getAudit({ reduceId: bizseq })
            if (+code === 200) {
                this.basicPrjDetail = data
            }
        },
        // 流程按钮
        handleBtn(val) {
            console.log(val);
            this[val]()
        },
        // 保存数据 下一步不提示
        async saveData(type = true) {
            if (!this.basicPrjDetail.isNormalLoss) {
                this.$message.warning('请选择该项目是否为正常损耗！')
                throw ""
            }
            await this.$refs['ReviewReducerOders'][0]?.saveInfo(type)
            await this.getAuditInfo(this.workDetail?.bizObject?.bizSeq)
        },
        // 物资退库
        async sendCancellStocks() {
            const params = { auditDeclineId: this.workDetail?.bizObject?.bizSeq }
            const { code } = await getMaterialReturn(params)
            if (+code === 200) {
                await this.nextPageResVerfic()
            }
        },
        // 提交
        async startProcess() {
            // 保存数据
            await this.saveData(false)
            // 后端校验
            const { code } = await getSubmitCheck({ reduceId: this.workDetail?.bizObject?.bizSeq })
            if (+code !== 200) {
                return Promise.reject()
            }
            // 校验数据
            this.doNextPageVerfic()
            // 校验主设备
            await this.$refs['ReviewReducerOders'][0]?.checkYYMD()
            this.nextVisible = true
        },
        doNextPageVerfiOne(data) {
            return ["", null].includes(data.keeper) || ["", null].includes(data.keeperAddress) || ["", null].includes(data.keeperContact);
        },
        doNextPageVerfiTwo(data) {
            return (!['0', null].includes(data.materialUsableNoStock)) || (!['0', null].includes(data.materialDisableNoStock))
        },
        doNextPageVerficNextTo(_isNormalLoss, reduceAmount) {
            let result4 = ["", null].includes(_isNormalLoss);
            if (result4) {
                this.$message.error("请选择该项目是否为正常损耗！");
                throw ""
            }
            if (+reduceAmount >= 500 && _isNormalLoss == "0") {
                this.$message.error("无实物审减金额之和大于500元，该项目只能为非正常损耗，请修改！");
                throw ""
            }
        },
        doNextPageVerfic() {
            const _isNormalLoss = this.basicPrjDetail.isNormalLoss
            const dataArray = this.$refs['ReviewReducerOders'][0]?.tableData
            let reduceNum = 0;
            //审减金额
            let reduceAmount = 0;
            for (let i = 0; i < dataArray.length; i++) {
                let data = dataArray[i];
                reduceNum = reduceNum + data.mdseNum;
                reduceAmount = reduceAmount + data.noMaterialReduceAmount;
                //校验有实物可用不入库和有实物不可用不入库是否填写了保管人、保管人电话、保管人地址
                if (this.doNextPageVerfiTwo(data)) {
                    let result2 = this.doNextPageVerfiOne(data)
                    if (result2) {
                        this.$message.error("有实物可用不入库和有实物不可用不入库的订单请填写保管人、保管人电话、保管人地址等信息！");
                        throw ""
                    }
                }
                //校验审减数量是否和填写数量之和相等
                let mdseNum = data.mdseNum;
                let amount = Math.round(mdseNum * 10000 + data.materialUsableStock * 10000 + data.materialUsableNoStock * 10000 + data.materialDisableStock * 10000 + data.materialDisableNoStock * 10000 + data.noMaterialDisableNoStock * 10000);
                if (amount !== 0) {
                    this.$message.error("每条订单填写退库数量之和必须和商合订单审减数量相同！");
                    throw ""
                }
            }
            this.doNextPageVerficNextTo(_isNormalLoss, reduceAmount)
        },
        // 下一步
        async doNext() {
            if (this.workDetail.activityDefID === 'reduce2_cs05') {
                if (+this.basicPrjDetail.isPush === 0) {
                    this.$message.error('未通知仓储退库入库，请先进行物资退库再进行操作！')
                    throw ""
                }
                await this.nextPageResVerfic(false)
            }
            // 获取路由
            const { code, data } = await getRouteParams({ reduceId: this.workDetail?.bizObject?.bizSeq, currentNodeId: this.workDetail?.activityDefID })
            if (+code !== 200) {
                return Promise.reject()
            }
            this.routetype = data !== null ? data.toString() : data
            this.nextVisible = true
        },
        // 回退
        async doBack() {
            if (+this.basicPrjDetail.isPush === 1) {
                this.$message.error('已通知仓储退库入库，不允许回退！')
                throw ""
            }
            this.backVisible = true
        },
        // 转派
        async doReassign() {
            this.transferPageVisible = true
        },
        async doClose() {
            clonePage()
        },
        // 节点5才会调用
        async nextPageResVerfic(types = true) {
            const result = await getSpecialCheck({ auditDeclineId: this.workDetail?.bizObject?.bizSeq, prjId: this.workDetail?.bizObject?.prjId })
            if (+result.code !== 200) {
                return Promise.reject()
            }
            if (types) {
                this.$message.success(result.data)
            }
            await this.getAuditInfo(this.workDetail?.bizObject?.bizSeq)
        },
        // 下一步确认选人
        async nextPageRes(data) {
            // 前置校验
            const params = {
                adjustId: this.workDetail?.bizObject?.bizSeq,
                prjId: this.workDetail?.bizObject?.prjId,
                workFlowFlag: "doNext",
                nextNodeId: data.nodeId,
                workItemId: this.workDetail.workItemID,
                opinion: data.opinion,
                userIds: data.userId ? data.userId : data.empId,
                nextSceneId: "",
                currentPoint: this.workDetail.activityDefID
            }
            const { code } = await getConfirmPersonList(params)
            if (+code === 200) {
                this.$alert(`提交成功`, '系统提示', {
                    confirmButtonText: '确认',
                    cancelButtonClass: 'pms-zr-button',
                    callback: action => {
                        clonePage()
                    }
                })
            }
        },
        // 回退确认选人
        async backPageRes(data) {
            const params = {
                adjustId: this.workDetail?.bizObject?.bizSeq,
                prjId: this.workDetail?.bizObject?.prjId,
                workFlowFlag: "doBack",
                nextNodeId: data.nodeId,
                workItemId: this.workDetail.workItemID,
                opinion: data.opinion,
                userIds: data.userId ? data.userId : data.empId,
                nextSceneId: "",
                currentPoint: this.workDetail.activityDefID
            }
            const { code } = await getConfirmPersonList(params)
            if (+code === 200) {
                this.$alert(`提交成功`, '系统提示', {
                    confirmButtonText: '确认',
                    cancelButtonClass: 'pms-zr-button',
                    callback: action => {
                        clonePage()
                    }
                })
            }
        },
        // 转派确认选人
        async redeployEntity(data) {
            const params = {
                adjustId: this.workDetail?.bizObject?.bizSeq,
                prjId: this.workDetail?.bizObject?.prjId,
                workFlowFlag: "doReassign",
                nextNodeId: data.nodeId,
                workItemId: this.workDetail.workItemID,
                opinion: data.opinion,
                userIds: data.userId ? data.userId : data.empId,
                nextSceneId: "",
                currentPoint: this.workDetail.activityDefID
            }
            const { code } = await getConfirmPersonList(params)
            if (+code === 200) {
                this.$alert(`转派成功`, '系统提示', {
                    confirmButtonText: '确认',
                    cancelButtonClass: 'pms-zr-button',
                    callback: action => {
                        clonePage()
                    }
                })
            }
        }

    }
}

</script>
<style lang="scss" scoped></style>